package co.edu.udem.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import co.edu.udem.domain.Place;
import co.edu.udem.service.place.PlaceService;
import co.edu.udem.service.place.PlaceType;

/**
 * handles the place controller process.
 * 
 * @author sgranada
 * 
 */
@Controller
public class PlaceController extends BaseController {

	@Autowired
	private PlaceService placeService;

	@RequestMapping(value = "/place/manage", method = RequestMethod.GET)
	public String getSubjecDetailtList(Model model) {

		logger.debug("Request recibido para mostrar los lugares.");
		List<Place> placeList = placeService.getPlaceListByCriteria(null);
		model.addAttribute("placeList", placeList);
		return "placepage";
	}

	@RequestMapping(value = "/place/add", method = RequestMethod.GET)
	public String showAddPlacePage(Model model) {
		model.addAttribute("placeAttribute", new Place());
		model.addAttribute("placeTypeList", PlaceType.getCodesAsList());
		return "addplacepage";
	}

	@RequestMapping(value = "/place/add", method = RequestMethod.POST)
	public String addPlace(Model model,
			@ModelAttribute("placeAttribute") Place place) {
		model.addAttribute("placeAttribute", new Place());
		place.setPlaceTypeDescription(PlaceType
				.getPlaceTypeDescriptionByCode(place.getPlaceType()));
		place.setLatitude(Double.valueOf(place.getLatitudeString()));
		place.setLongitude(Double.valueOf(place.getLongitudeString()));
		placeService.save(place);
		return "addedplacepage";
	}
	
	@RequestMapping(value = "/place/edit", method = RequestMethod.GET)
	public String edit(@RequestParam("id") String placeCode, Model model) {
		Place place = placeService.getPlaceById(placeCode);
		place.setLongitudeString(place.getLongitude().toString());
		place.setLatitudeString(place.getLatitude().toString());
		model.addAttribute("placeAttribute", place);
		model.addAttribute("placeTypeList", PlaceType.getCodesAsList());
		return "addplacepage";
	}
	
	@RequestMapping(value = "/place/delete", method = RequestMethod.GET)
	public String delete(@RequestParam("id") String placeCode) {
		placeService.delete(placeCode);
		return "deletedplacepage";
	}
}
